<template>
  <view class="container">


    <view class="user-section">
      <view v-if="userStore.isLoggedIn" class="user-info">
        <image :src="userProfile.avatar_url || '/static/default-avatar.png'" class="avatar" mode="aspectFill"/>
        <view class="user-details">
          <text class="username">{{ userProfile.nickname || t('profile.page.notSetNickname') }}</text>
          <text class="user-id">{{ t('profile.page.userId') }}: {{ userStore.userId }}</text>
          <text class="user-email">{{ userProfile.email || t('profile.page.notSetEmail') }}</text>
          <text v-if="userProfile.phone" class="user-phone">{{ userProfile.phone }}</text>
          <text v-if="userProfile.user_type" class="user-type">{{ t('profile.page.userType') }}: {{ userProfile.user_type }}</text>
        </view>
      </view>

      <view v-else class="login-prompt">
        <text class="prompt-text">{{ t('profile.page.pleaseLogin') }}</text>
        <button class="login-btn" @click="goToLogin">{{ t('profile.page.loginNow') }}</button>
      </view>
    </view>

    <!-- 用户统计信息 -->
    <view v-if="userStore.isLoggedIn" class="stats-section">
      <view class="stats-grid">
        <view class="stats-item">
          <text class="stats-label">{{ t('profile.page.registerTime') }}</text>
          <text class="stats-value">{{ formatDate(userProfile.create_time) }}</text>
        </view>
        <view class="stats-item">
          <text class="stats-label">{{ t('profile.page.lastLogin') }}</text>
          <text class="stats-value">{{ formatDate(userProfile.last_login) }}</text>
        </view>
      </view>
    </view>

    <view class="menu-section">
      <view class="menu-item" @click="goToEdit">
        <text class="menu-text">{{ t('profile.page.editProfile') }}</text>
        <text class="menu-arrow">></text>
      </view>
      <view class="menu-item" @click="gotoLearnlist">
        <text class="menu-text">{{ t('profile.page.learningRecord') }}</text>
        <text class="menu-arrow">></text>
      </view>
    </view>

    <view v-if="userStore.isLoggedIn" class="logout-section">
      <tui-button class="logout-btn" shape="circle" type="danger" @click="showLogoutModal">{{ t('profile.logout') }}</tui-button>
    </view>

    <!-- 退出登录确认弹窗 -->
    <tui-modal :show="logoutModalVisible" :content="t('profile.page.logoutConfirmContent')" :title="t('profile.page.logoutConfirmTitle')" @cancel="hideModal"
               @click="handleModalClick"/>
  </view>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {useUserStore} from '@/stores/user'
import {userApi} from '@/utils/api'
import { useI18n } from '@/composables/useI18n'
import { usePageTitle } from '@/composables/usePageTitle'
import { useTabBar } from '@/composables/useTabBar'

const userStore = useUserStore()
const { t } = useI18n()

// 设置页面标题
usePageTitle('pages/profile/index')

// 设置tabBar
useTabBar()

// 用户资料数据
const userProfile = reactive({
  nickname: '',
  email: '',
  phone: '',
  avatar_url: '',
  user_type: '',
  create_time: '',
  last_login: ''
})

// 退出登录弹窗状态
const logoutModalVisible = ref(false)

// 获取用户资料
const fetchUserProfile = async () => {
  if (!userStore.userId) {
    console.log('用户未登录或用户ID无效')
    return
  }

  try {
    const data = await userApi.getUserProfile(userStore.userId)
    console.log('获取到的用户资料:', data)

    // 更新用户资料数据
    Object.assign(userProfile, {
      nickname: data.nickname || '',
      email: data.email || '',
      phone: data.phone || '',
      avatar_url: data.avatar_url || '',
      user_type: data.user_type || '',
      create_time: data.create_time || '',
      last_login: data.last_login || ''
    })
  } catch (err: any) {
    console.error('获取用户资料失败:', err)
    uni.showToast({
      title: '获取用户资料失败',
      icon: 'none'
    })
  }
}

// 跳转到登录页面
const goToLogin = () => {
  console.log('尝试跳转到登录页面')
  uni.navigateTo({
    url: '/pages/auth/login',
    success: () => {
      console.log('跳转成功')
    },
    fail: (err) => {
      console.error('跳转失败:', err)
      // 如果登录页面跳转失败，使用原生modal
      uni.showModal({
        title: t('common.info'),
        content: t('error.pageNotOpen'),
        showCancel: false
      })
    }
  })
}

// 跳转到编辑资料页面
const goToEdit = () => {
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: t('profile.page.pleaseLogin'),
      icon: 'none'
    })
    return
  }
  uni.navigateTo({
    url: '/pages/profile/edit'
  })
}
const gotoLearnlist = () => {
  uni.navigateTo({
    url: '/pages/profile/learnlist'
  })
}

// 显示弹窗
const showLogoutModal = () => {
  console.log('显示退出登录弹窗')
  logoutModalVisible.value = true
  console.log('弹窗状态:', logoutModalVisible.value)
}

// 隐藏弹窗
const hideModal = () => {
  console.log('隐藏弹窗')
  logoutModalVisible.value = false
}

// 处理弹窗点击事件
const handleModalClick = (e: any) => {
  console.log('Modal click event:', e)
  let index = e.index
  if (index === 0) {
    console.log('你点击了取消按钮')
    hideModal()
  } else {
    console.log('你点击了确定按钮')
    userStore.logout()
    hideModal()
    uni.showToast({title: t('profile.page.logoutSuccess'), icon: 'success'})
  }
}


// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return t('profile.page.unknown')
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  } catch (error) {
    return t('profile.page.unknown')
  }
}

// 页面加载时获取用户资料
onMounted(() => {
  if (userStore.isLoggedIn) {
    fetchUserProfile()
  }
})
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f8f9fa;
}

.header {
  background: white;
  padding: 40rpx;
  text-align: center;
  border-bottom: 1rpx solid #e9ecef;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.user-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 40rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-right: 30rpx;
}

.user-details {
  flex: 1;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.user-id {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
  display: block;
}

.user-email {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.user-phone {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.user-type {
  font-size: 22rpx;
  color: #999;
  display: block;
  background: #f8f9fa;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  width: fit-content;
}

.login-prompt {
  text-align: center;
  padding: 40rpx 0;
}

.prompt-text {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
  display: block;
}

.login-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

.menu-section {
  margin-top: 60rpx;
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.2s ease;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item:active {
  background-color: #f8f9fa;
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.menu-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.menu-arrow {
  font-size: 24rpx;
  color: #999;
}

.logout-section {
  margin: 20rpx;
  padding: 40rpx 0;
}

.logout-btn {
  width: 100%;
  opacity: 0.8;
}

.stats-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.stats-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  text-align: center;
}

.stats-grid {
  display: flex;
  justify-content: space-around;
}

.stats-item {
  text-align: center;
  flex: 1;
}

.stats-label {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.stats-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
}
</style>